<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      ref="crud"
      v-model="form"
      @row-del="rowDel"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @current-change="currentChange"
      @size-change="sizeChange"
      @on-load="onLoad"
    >
      <template slot-scope="{ type, size, row, index }" slot="menu">
        <el-button
          icon="el-icon-edit"
          :size="size"
          :type="type"
          @click="editRow(row, index)"
          >编辑</el-button
        >
        <el-button
          icon="el-icon-delete"
          :size="size"
          :type="type"
          @click="rowDel(row)"
          >删除</el-button
        >
        <el-switch
          :value="row.status === 1"
          @input="(val) => handleSwitch(row, val)"
          size="small"
          active-text="上下架"
          class="switch"
        ></el-switch>
      </template>
      <template slot="contentForm">
        <el-row>
          <tinymce-editor v-model="content" ref="editor"></tinymce-editor>
        </el-row>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
import {
  add,
  getList,
  remove,
  update,
  getCategoryTree,
} from "@/api/article/list";
import { mapGetters } from "vuex";
import TinymceEditor from "../../components/tinymce-editor/tinymce-editor";

export default {
  components: {
    TinymceEditor,
  },
  data() {
    return {
      form: {},
      loading: true,
      content: "",
      dialogFormVisible: false,
      articleFullscreen: false,
      formLabelWidth: 200,
      query: {},
      categoryOptions: [],
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      option: {
        border: true,
        align: "left",
        menuAlign: "center",
        columnBtn: false,
        refreshBtn: false,
        delBtn: false,
        editBtn: false,
        index: true,
        column: [
          {
            label: "文章名称",
            prop: "title",
            formatter: function (row, value, label) {
              return '<span style="color: #409EFF;">' + row.title + "</span>";
            },
          },
          {
            label: "作者",
            prop: "author",
          },
          {
            label: "文章分类",
            prop: "categoryId",
            type: "tree",
            dicUrl: "/api/blade-article/article/category/query",
            props: {
              label: "name",
              value: "id",
            },
            rules: [
              {
                required: true,
                message: "请选择文章分类",
                trigger: "click",
              },
            ],
          },
          {
            label: "文章链接",
            prop: "url",
          },
          {
            label: "文章简介",
            prop: "introduction",
            type: "textarea",
            hide: true,
            rules: [
              {
                required: true,
                message: "请填写文章简介",
                trigger: "click",
              },
            ],
            span: 24,
            maxlength: 200,
          },
          {
            label: "内容",
            prop: "content",
            span: 24,
            hide: true,
            slot: true,
          },
          {
            label: "项目图片",
            type: "upload",
            listType: "picture-img",
            propsHttp: {
              res: "data",
              url: "fileUrl",
            },
            canvasOption: {
              text: " ",
              ratio: 0.1,
            },
            action: "/api/blade-file/file/uploadFile",
            tip: "只能上传jpg/png用户头像，且不超过500kb",
            span: 12,
            row: true,
            prop: "imgUrl",
          },
        ],
      },
      data: [],
    };
  },
  computed: {
    editor() {
      return this.$refs.myQuillEditor.quill;
    },
  },
  created: function () {
    getCategoryTree(1, 10).then((res) => {
      this.categoryOptions = res.data.data;
    });
  },
  mounted() {
    let content = ""; // 请求后台返回的内容字符串
    this.str = this.escapeStringHTML(content);
  },
  methods: {
    editRow(row, index) {
      this.form = row;
      this.content = this.escapeStringHTML(row.content);
      this.$refs.crud.rowEdit(row, index);
    },
    handleAdd() {
      this.dialogFormVisible = true;
    },
    deleteRow(row) {
      this.form = row;
      this.content = row.content;
      this.dialogFormVisible = true;
    },
    rowSave(row, done, loading) {
      let that = this;
      row.content = this.content;
      //新增
      add(row).then(
        () => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.content = "";
          that.clear();
          console.log(row);
        },
        (error) => {
          window.console.log(error);
          loading();
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      let that = this;
      row.content = this.content;
      //修改
      update(row).then(
        () => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.content = "";
          that.clear();
        },
        (error) => {
          window.console.log(error);
          loading();
        }
      );
    },
    rowDel(row) {
      //删除
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        });
    },
    currentChange(currentPage) {
      //分页页码
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      //分页条数
      this.page.pageSize = pageSize;
    },
    onLoad(page, params = {}) {
      //调用接口初始化
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      ).then((res) => {
        this.data = res.data.data.records;
        this.loading = false;
        // console.log(this.data);
      });
    },
    escapeStringHTML(str) {
      //把实体格式字符串转义成HTML格式的字符串
      var arrEntities = { lt: "<", gt: ">", nbsp: " ", amp: "&", quot: '"' };
      return str.replace(/&(lt|gt|nbsp|amp|quot);/gi, function (all, t) {
        return arrEntities[t];
      });
    },
    escapeHTMLString(str) {
      str = str.replace(/</g, "&lt;");
      str = str.replace(/>/g, "&gt;");
      return str;
    },
    //上下架文章
    async handleSwitch(row, bool) {
      // console.log(row, bool);
      row.status = bool ? 1 : 0;
      await update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        },
        (error) => {
          window.console.log(error);
        }
      );
      // this.onLoad(this.page);
    },
    //清空内容
    clear() {
      this.$refs.editor.clear();
    },
    submitForm() {
      if (!this.content) {
        this.$message({
          message: "请先输入完整的文章内容",
          type: "warning",
        });
      } else {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            this.form.content = this.escapeHTMLString(this.content);
            add(this.form).then(
              () => {
                this.onLoad(this.page);
                this.$message({
                  type: "success",
                  message: "操作成功!",
                });
                this.dialogFormVisible = false;
              },
              (error) => {
                window.console.log(error);
                loading();
              }
            );
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.preview {
  min-height: 150px;
}

::v-deep .el-dialog__header {
  padding: 16px 24px;
  min-height: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.articleForm .el-select,
.articleForm .el-input {
  width: 360px;
}

.ueditor-wrap {
}

::v-deep .ueditor-content .el-form-item__label {
  width: 100%;
  float: none;
}

::v-deep .ueditor-content .el-form-item__content {
  margin: 0 !important;
}
</style>
